package Dm

import (
	"fmt"
	"db2s/ETL"
	"db2s/global"
	"strings"
)

func (or TableInfoMeta) CustomizeTypeExist(s global.TablesMetaInfoInput) (result global.ObjectExistReturnResult, err error) {
	var f1 any
	var event = "[oracleCustomizeTypeExist]"
	for _, v := range []string{
		"ALL_TYPES", "DBA_TYPES",
	} {
		result.BaseResult.Sql = fmt.Sprintf("select count(1) as \"sum\" from %v WHERE OWNER = '%v' and TYPE_NAME = '%v'", v, s.TableInfo.Schema, s.TableInfo.Table)
		if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
			Ss:           s,
			Event:        event,
			SelectSqlStr: result.BaseResult.Sql,
			Expect:       ETL.Map,
		}); err != nil {
			continue
		}
		if fmt.Sprintf("%v", f1.(map[string]any)["sum"]) == "1" {
			result.Result = true
		}
		break
	}

	return
}

func (or TableInfoMeta) CustomizeTypeName(s global.TablesMetaInfoInput) (result global.ObjectNameReturnResult, err error) {
	var f1 any
	var event = "[oracleCustomizeTypeName]"
	for _, v := range []string{
		//"USER_TYPES",
		"ALL_TYPES",
		"DBA_TYPES",
	} {
		result.BaseResult.Sql = fmt.Sprintf("select TYPE_NAME from %v where OWNER ='%v' %v",
			v, s.TableInfo.Schema, func() string {
				switch {
				case s.TableInfo.Table == "*":
					return ""
				case strings.Contains(s.TableInfo.Table, "%"):
					return fmt.Sprintf(" and TYPE_NAME like '%%%v%%'", s.TableInfo.Table)
				default:
					return fmt.Sprintf(" and TYPE_NAME = '%v'", s.TableInfo.Table)
				}
			}())
		if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
			Ss:           s,
			Event:        event,
			SelectSqlStr: result.BaseResult.Sql,
			Expect:       ETL.StringGarth,
		}); err != nil {
			continue
		}
		result.Result = f1.([]string)
		break
	}
	return
}

func typePrintInfo(x global.TypeResultDefinition) (res string) {
	/*
		CREATE OR REPLACE TYPE "PCMS"."F_GCJ" as object (gcj_lat number, gcj_lon number);
		CREATE OR REPLACE TYPE "PCMS"."SEQ_ARRAY" is table of number;
		CREATE OR REPLACE TYPE "PCMS"."OPTICABSEG_OBJ" as object (
		  id                NUMBER(10),
		  name              NVARCHAR2(500),
		  city_id           NUMBER(10),
		  county_id         NUMBER(10),
		  typecode          NUMBER(10),
		  status            NUMBER(10),
		  pro_task_id       NUMBER(10),
		  is_complete_lay   NUMBER(10),
		  related_system    NUMBER(10),
		  a_id              NUMBER(10),
		  a_type            NUMBER(10),
		  z_id              NUMBER(10),
		  z_type            NUMBER(10),
		  system_level      NUMBER(10),
		  wkt               NVARCHAR2(500),
		  shape             clob
		);
	*/
	res = fmt.Sprintf("CREATE OR REPLACE %v"+
		"/",
		x.Body,
	)
	return
}
func getTypeBody(s global.SchemaObjectInput) (res string, err error) {
	var (
		event = "[oracleGetTypeBody]"
		f1    any
		r     []string
	)
	sqlStr := fmt.Sprintf("SELECT \n"+
		"\t\"TEXT\" AS \"text\" \n"+
		"FROM \n"+
		"all_source where 1=1 \n"+
		"\tAND TYPE = 'TYPE' \n"+
		"\tAND OWNER='%v' \n"+
		"\tAND NAME='%v' ORDER BY LINE", s.Schema, s.Table)
	if _, f1, err = ExecSelectSql(ExecSqlInputS{
		Ss:           s,
		Event:        event,
		SelectSqlStr: sqlStr,
		Expect:       ETL.SMap,
	}); err != nil {
		return
	}
	for _, v := range f1.([]map[string]any) {
		r = append(r, fmt.Sprintf("%v", v["text"]))
	}
	res = strings.Join(r, "")
	return
}
func typeDefinitionConvert(x global.TypeResultDefinition) (convert global.TypeDefinitionConvertS) {
	return global.TypeDefinitionConvertS{
		Schema:    x.Schema,
		Name:      x.Name,
		Body:      x.Body,
		Comment:   x.Comment,
		Type:      x.Type,
		PrintInfo: x.PrintInfo,
	}
}
func (or SchemaObjectMeta) Type(s global.SchemaObjectInput) (res global.SchemaObjectReturnResult, err error) {
	var (
		x global.TypeResultDefinition
	)
	x.Schema = s.Schema
	x.Name = s.Table
	if x.Body, err = getTypeBody(s); err != nil {
		return
	}
	x.PrintInfo = typePrintInfo(x)
	res.TypeResult.Definition = x
	res.TypeResult.Convert = typeDefinitionConvert(x)
	return
}
